<?php

namespace Api\Controller;

use Think\Controller;

//加载commons下的functions.php自定义函数库
load("@.functions");

/**
 * Description of EquipmentApiController
 *
 * @author Shangyidong
 */
class ImageApiController extends Controller {

    //put your code here
    function get_url() {
        //验证app_key
        verify_app_key(I('post.app_key'));
        $id = I('get.id');
        $result['code'] = "200";
        if ($id == '' || !is_numeric($id) || $id <= 0) {
//            echo '{"info":"请输入正确的id"}';
            $result['code'] = "1070101";
//            $result['reason'] = "请输入正确的图片id";
            echo json_encode($result, JSON_PRETTY_PRINT);
            die();
        }
        $Image = new \Common\Model\ImageModel();
        $image = $Image->where("id = " . $id)->find();
        $result['result'] = $image;
        echo json_encode($result, JSON_PRETTY_PRINT);
    }

    /**
     * 采用普通上传方式上传文件
     * http://www.open-open.com/lib/view/open1340616634077.html
     */
    function upload_head_icon() {
        $result['code'] = "200";
        header("Content-Type: text/html; charset=utf-8");
        verify_app_key(I('post.app_key'));
        $user = verify_token(I('post.token'));
        //验证通过才能继续向下执行
        $date = date("Y-m-d H:i:s"); //2015-05-13 16:29:37
        $year = substr($date, 0, 4); //2015
        $month = substr($date, 5, 2); //05
        $day = substr($date, 8, 2); //13
        $dir = './Public/uploads/' . $year . '/' . $month . '/' . $day . '/';
        //echo $dir;
        create_dir($dir); //调用公共函数
        //$target_path = "./upload/"; //接收文件目录 
        //$target_path = $dir . basename($_FILES['file']['name']);
//        show_bug($_FILES["file"]);
        /*
          echo "dir: " . $target_path . '<br/>';
          echo "Upload: " . $_FILES["file"]["name"] . "<br />";
          echo "Type: " . $_FILES["file"]["type"] . "<br />";
          echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
          echo "Stored in: " . $_FILES["file"]["tmp_name"];
         */
        if ($_FILES["file"]["size"] / 1024 > 2 * 1024.0) {
            //上传的图片过大！
            $result['code'] = "1070201";
            echo json_encode($result, JSON_PRETTY_PRINT);
            die();
        }

        if ($_FILES["file"]["type"] == "image/gif") {
            $target_path = $dir . create_uuid("ico_") . '.gif';
        } else if ($_FILES["file"]["type"] == "image/pjpeg") {//对于 IE，识别 jpg 文件的类型必须是 pjpeg，对于 FireFox，必须是 jpeg。
            $target_path = $dir . create_uuid("ico_") . '.pjpeg';
        } else if ($_FILES["file"]["type"] == "image/jpeg") {
            $target_path = $dir . create_uuid("ico_") . '.jpeg';
        } else if ($_FILES["file"]["type"] == "image/png") {
            $target_path = $dir . create_uuid("ico_") . '.png';
        } else {
            //上传的图片格式错误
            $result['code'] = "1070202";
            echo json_encode($result, JSON_PRETTY_PRINT);
            die();
        }
        $image_name = $_FILES["file"]["name"];
        $image_url = $target_path;
        if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
//            echo "The file " . basename($_FILES['file']['name']) . " has been uploaded"; //上传成功
            //①从dic_table中查出user表的table_id
            $Dic_tableModel = new \Common\Model\Dic_tableModel();
            $dic_table = $Dic_tableModel->get_id_by_name(C('DB_PREFIX') . "user");
            //②获取user在user表中的id即为id_in_that_tab
            $table_id = $dic_table['id'];
            $id_in_that_tab = $user['id'];
            $ImageModel = new \Common\Model\ImageModel();
            //上传新的头像之后更新数据库并且删除旧的头像
            $oldImage = $ImageModel->where("table_id = " . $table_id . " and id_in_that_tab = " . $id_in_that_tab)->find();
            if ($oldImage == null) {
                $ImageModel = new \Common\Model\ImageModel();
                $image['img_name'] = "";
                $image['img_url'] = $target_path;
                $image['table_id'] = $table_id;
                $image['id_in_that_tab'] = $id_in_that_tab;
                $image['memo'] = $user['phone'] . "的头像";
                $id = $ImageModel->add($image);
                $image['id'] = $id;
                $result['result'] = $image;
//                echo $ImageModel->getLastSql();
            } else {
                $old_url = $oldImage['img_url'];
                $oldImage['img_url'] = $target_path;
                $ImageModel->save($oldImage);
//            $ImageModel = new \Common\Model\ImageModel();
//            $ImageModel->where("table_id = " . $table_id . " and id_in_that_tab = " . $id_in_that_tab)->delete();
//            echo '删除：'.$ImageModel->where("table_id = " . $table_id . " and id_in_that_tab = " . $id_in_that_tab)->delete().'<br/>';
//            show_bug($oldImage);
                /*
                  echo APP_ROOT_DIR.'<br/>';
                  echo 'oldImage[img_url]:' . $oldImage['img_url'] . '<br/>';
                  echo is_file($oldImage['img_url']);
                  echo '文件路径：'.APP_ROOT_DIR.  substr($oldImage['img_url'], 1, strlen($oldImage['img_url']) - 1).'<br/>';
                  if(! is_file(APP_ROOT_DIR.  substr($oldImage['img_url'], 1, strlen($oldImage['img_url']) - 1))){
                  echo '不是文件';
                  //                die();
                  }
                 * */

                @chmod($oldImage['img_url'], 0777);

                if (!unlink($old_url)) {
                    /*
                      }
                      $this->on_error('Can\'t delete file!', 309); //出错处理
                      echo '不能删除旧文件';
                      exit;
                     */
                }
                $result['result'] = $oldImage;
            }


            echo json_encode($result, JSON_PRETTY_PRINT);
        } else {
//            echo "There was an error uploading the file, please try again!" . $_FILES['file']['error'];
            $result['code'] = "500";
            echo json_encode($result, JSON_PRETTY_PRINT);
        }
    }

}
